#!/usr/local/bin/python3
#encoding:utf-8

#import urllib
from urllib.parse import urlparse
import urllib.request
import datetime
from bs4 import BeautifulSoup
from Base64EncoderDecoder import *

def piaohua_a_movie(title, url):
    while(True):
        try:
            page = urllib.request.urlopen(url)
        except IOError:
            print('Error open URL:'),
            print(url)
        else:
            if page != None:
                break;
    soup = BeautifulSoup(page)
    div_show = soup.find('div', id='show')
    movie_attr = { "title":"title", "url":"url"}
    movie_attr['title'] = div_show.find('h3').contents[0].strip()
    print(movie_attr['title'])
    div_showinfo = soup.find('div', id="showinfo")
    for table in div_showinfo.findAll('table'):
        for anchor in table.findAll('a'):
            if urlparse(anchor['href']).scheme != 'http':
                print((urlencode(anchor['href'])))
    return movie
        #if table.find('anchor') != None:
            #print(table.find('anchor'))
            #print(table.find('anchor')['href'])
            #str_url = (table.find('anchor')['href'])
            #print(urlencode(str_url))

#if __name__ == "__main__":
requrl = "http://www.piaohua.com/html/zuixindianying.html"
ph_url = "http://www.piaohua.com"
page = urllib.request.urlopen(requrl)
soup = BeautifulSoup(page)
div_im = soup.find('div',id='im')
for div_bunews in div_im.findAll('div', class_="bunews"):
    movie_class = div_bunews.find('div', class_='title').contents[1].contents[0]
    if movie_class == u"最新纪录片":
        continue
    for li in div_bunews.findAll('li'):
        if li.find('a').find('font') != None:
            title = li.find('a').find('font').contents[0]
            url = li.find('a')['href']
            #print(title)
            piaohua_a_movie(title, ph_url+url)
        else:
            title = li.find('a').contents[0]
            url = li.find('a')['href']
            #print(title)
            piaohua_a_movie(title, ph_url+url)

        #print(u"\n")
        #break
        #print(li.contents[1].contents[0].contents[0]

